package dbutils02;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Before;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * BeanListHandler:将查询结果集中的每一行都封装成一个个 JavaBean 对象,然后再把这些对
 象存储到一个 List 集合中
 * QueryRunner 类中
 * <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
 * MapHandler:将查询结果集的第一行封装到一个 Map<String,Object>,Map 中的 key 代表列名
 称,value 代表该列对应的值
 * MapListHandler:将查询结果集的每一行数据都封装到一个 Map<String,Object>中,Map 中的
 key 代表列名称,value 代表该列对应的值
 * 将所有的 Map<String,Object>添加到一个 List<Map<Strig,Object>>集合
 中,最终返回这个 List<Map<Strig,Object>>集合
 * ScalarHandler:封装的是单行单列的数据,一般针对 SQL 语句中聚合函数结果集
 */

public class DBUtilsDemo04 {
    private QueryRunner qr;
    @Before
    public void  initQueryRunnner(){
        qr = new QueryRunner(JDBCUtils.getDataSource());
    }
    @Test
    public  void  testBeanListHandler() throws SQLException {
        //1.查询价格在3000-8000商品
        List<Product> p = qr.query("select * from product where price BETWEEN ? and ?", new BeanListHandler<Product>(Product.class, new BasicRowProcessor((new GenerousBeanProcessor())))
                , 3000, 8000);
        p.stream().forEach(System.out::println);
    }
    @Test
    public  void testMapHandler() throws SQLException {
        Map<String, Object> map = qr.query("select * from product", new MapHandler(new BasicRowProcessor(new GenerousBeanProcessor())));
        map.forEach((key,value)-> System.out.println(key+"="+value));
    }
    @Test
    public  void testMapListHandler() throws SQLException {
        List<Map<String, Object>> mapList = qr.query("select * from product", new MapListHandler(new BasicRowProcessor(new GenerousBeanProcessor())));
        mapList.stream().forEach(System.out::println);
    }
    @Test
    public void testScalarHandler() throws SQLException {
        Long count= qr.query("select count(*) from product", new ScalarHandler<Long>());
        System.out.println(count);
    }
}
